<?php
namespace App\Admin\Controllers\System;

use App\Admin\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Admin\Models\DictType;

use App\Admin\Actions\DataTable;
use App\Admin\Actions\SoftDelete;
use App\Admin\Actions\Create;
use App\Admin\Actions\Update;
use App\Admin\Actions\Delete;

class DictTypeController extends Controller
{
	use DataTable, SoftDelete, Create, Update, Delete;

	public function modelName()
	{
		return DictType::class;
	}

	public function dataTable($setter)
	{
		$setter->validate(function($request){
			return $request->validate([
				'name'   => 'nullable|string|between:2,20',
				'code'   => 'nullable|string|between:2,20',
				'status' => 'nullable|integer|boolean',
			]);
		});

		$setter->search(function($query, $validated){
			if( !empty($validated['name']) ){
				$query->where('name', $validated['name']);
			}

			if( !empty($validated['code']) ){
				$query->where('code', $validated['code']);
			}
		});
	}

	public function storeAndUpdateValidate($request, $model=null)
	{
		if( $model ){
			$unique = Rule::unique(DictType::class)->ignore($model);
			$rules = [
				'name'     => ['sometimes', 'alpha_num', 'between:2,50', $unique],
				'code'     => ['sometimes', 'regex:/^[a-zA-Z][a-zA-Z0-9_]{0,18}[^_]$/i', $unique],
				'status'   => 'sometimes|integer|boolean',
			];

		}else{
			$unique = Rule::unique(DictType::class);
			$rules = [
				'name'     => ['required', 'alpha_num', 'between:2,50', $unique],
				'code'     => ['required', 'regex:/^[a-zA-Z][a-zA-Z0-9_]{0,18}[^_]$/i', $unique],
				'status'   => 'required|integer|boolean',
			];
		}

		$name = $request->input('name');
		$code = $request->input('code');
		return $request->validate($rules, [
			'required'    => ':attribute不能为空',
			'unique'      => ':attribute已存在',
			'code.regex'  => '字典标识格式20位以内的字母、数字、下划线_组合, 只能以字母开头，不能以下划线结尾',
			'name.unique' => "字典名称 `{$request->input('name')}` 已存在",
			'code.unique' => "字典标识 `{$code}` 已存在",
		], [
			'name' => '字典名称',
			'code' => '字典标识',
			'status' => '字典状态',
		]);
	}
}
